package com.kanshu.ksgb.fastread.doudou.base.baseui;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.gyf.barlibrary.ImmersionBar;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.imageloader.GlideImageLoader;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog;
import com.kanshu.ksgb.fastread.doudou.common.view.TitlebarView;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.NotifyBean;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
/**
 * BaseActivity
 * Created by wcy on 2017/4/13.
 */
public class BaseActivity extends SwipeBackActivity {
    protected TitlebarView mTitle;
    protected FrameLayout mContent;
    protected View mTitlePlaceHolder;
    protected boolean mHasSaveInstanceState;
    protected ImmersionBar mImmersionBar;
    private SparseArray<View> mCommonViews;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onBeforeSetContentView();
        super.setContentView(R.layout.activity_base_layout);
        initView();
        setActivityTag();
    }


    private void initView() {
        mCommonViews = new SparseArray<>();
        mTitle = (TitlebarView) findViewById(R.id.title);
        mContent = (FrameLayout) findViewById(R.id.content);
        mTitlePlaceHolder = findViewById(R.id.title_place_holder);
        initStatusbar();
    }

    protected void initStatusbar() {
        try {
            mImmersionBar = ImmersionBar.with(this);
            mImmersionBar.keyboardEnable(true);
            mImmersionBar.init();
            if (ImmersionBar.isSupportStatusBarDarkFont())
                mImmersionBar.statusBarDarkFont(true).init();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int statusBarHeight = DisplayUtils.getStatusBarHeight(this);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mTitle.getLayoutParams();
        params.topMargin = statusBarHeight;
        mTitle.setLayoutParams(params);
    }

    protected void parseVipJpushChannel() {
        try {
            Uri data = getIntent().getData();
            if (data != null) {
                JSONObject object = new JSONObject(data.toString());
                String msgId = object.optString("msg_id");
                if(!TextUtils.isEmpty(msgId)){
                    JPushInterface.reportNotificationOpened(this, msgId, (byte) 2);
                }
                JSONObject jsonObject2 = object.optJSONObject("n_extras");
                String notify = jsonObject2.optString("notify");
                NotifyBean bean = JsonUtils.json2BeanByFastJson(notify, NotifyBean.class);
                parseVipJpush(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void parseVipJpush(NotifyBean bean){}

    public void setTitle(CharSequence s) {
        mTitle.setTitle(s);
    }

    public void setSubTitle(CharSequence s) {
        mTitle.setSubTitle(s);
    }

    public void setLeftTitle(CharSequence s) {
        mTitle.setLeftText(s);
    }

    public void hideTitlebar() {
        mTitle.setVisibility(View.GONE);
    }

    public void goneTitlebar() {
        goneTitlebar(true);
    }

    public void goneTitlebar(boolean hidePlaceHolder) {
        DisplayUtils.gone(mTitle);
        mTitlePlaceHolder.setVisibility(hidePlaceHolder ? View.GONE : View.VISIBLE);
    }

    public void goneTitlePlaceHolder() {
        DisplayUtils.gone(mTitlePlaceHolder);
    }

    public void goneTitleback() {
        DisplayUtils.gone(mTitle.getBack());
    }

    protected void onBeforeSetContentView() {
        mCommonViews = new SparseArray<>();
        // 无标题
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if (isNeedRemoveWindowBackground()) {
            getWindow().setBackgroundDrawable(null);
        }
    }

    protected boolean isNeedRemoveWindowBackground() {
        return true;
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        mContent.removeAllViews();
        LayoutInflater.from(this).inflate(layoutResID, mContent, true);
    }

    /**
     * 设置activity的tag
     */
    protected void setActivityTag() {
        if (getWindow() != null && getWindow().getDecorView() != null) {
            getWindow().getDecorView().setTag(getSpecifyTag());
        }
    }

    /**
     * 获取Activity指定的tag
     * @return
     */
    protected String getSpecifyTag() {
        return "";
    }
    @Override
    public void setContentView(View view) {
        mContent.removeAllViews();
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        mContent.addView(view, lp);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        mContent.removeAllViews();
        mContent.addView(view, params);
    }

    public TitlebarView getTitlebarView() {
        return mTitle;
    }

    public FrameLayout getContent() {
        return mContent;
    }

    public int getContentId() {
        return R.id.content;
    }

    public void showFragment(Fragment fragment, String tag) {
        if (fragment == null) {
            return;
        }
        try {
            FragmentTransaction trac = getSupportFragmentManager()
                    .beginTransaction();
            trac.replace(getContentId(), fragment, tag);
            trac.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addRightView(View v, ViewGroup.LayoutParams layoutParams) {
        mTitle.getRightContainer().addView(v, layoutParams);
    }

    public void setContentBgColor(int color) {
        mContent.setBackgroundColor(color);
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        GlideImageLoader.trimMemory(this, level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        GlideImageLoader.clearMemory(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHasSaveInstanceState = false;
        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);
        MobclickAgent.onPageEnd(getClass().getSimpleName());
        Utils.hideSoftKeyboard(this);
    }


    @Override
    public void onBackPressed() {
        FrameLayout adContainer = findViewById(R.id.ad_container_layout);
        if (adContainer != null && adContainer.getVisibility() == View.VISIBLE){
            AdUtils.destroyAd(adContainer);
            adContainer.removeAllViews();
            DisplayUtils.invisible(adContainer, findViewById(R.id.app_logo), findViewById(R.id.skipView));
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null) {
            try {
                mImmersionBar.destroy();
            } catch (Exception e) {

            }
        }
        lifeCyclerSubject.onNext(ACTION_DESTORY);
        GlideImageLoader.clearMemory(this);
        mCommonViews.clear();
    }

    LoadingDialog loadingDialog;

    public void showLoading(String msg) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this, msg);
        }
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    public void dismissLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
    }



    @Override
    public <T extends View> T findViewById(int id) {
        View view = mCommonViews.get(id);
        if (view == null) {
            view = super.findViewById(id);
            mCommonViews.put(id, view);
        }
        return (T) view;
    }
}
